
import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { Button, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import ImgCrop from 'antd-img-crop';

import * as qiniu from 'qiniu-js'
import { qiniuGetUploadToken, qiniuGetUrl } from '../../services';
import { uuid } from '../../utils';
import { UploadListType } from 'antd/lib/upload/interface';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

export interface QiniuFileUploadProps {
  onChange?: (files: Array<string>) => Promise<void>;
  values?: Array<string>;
  filePath: string;
  title?: string;
  max?: number;
  listType?: UploadListType;
  accept?: string;
  isPicture?: boolean;
}

export const QiniuFileUpload: React.FC<QiniuFileUploadProps> = (props) => {

  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const [values, setValues] = useState<Array<string>>([]);

  const customRequest = useCallback(async (options) => {
    console.log(options);
    const uploadConfig: qiniu.UploadConfig = {
      tokenProvider: async () => {
        // 线上应该使用服务端生成 token
        return await qiniuGetUploadToken();
      },
    }
    //从filename中获取到后缀
    let optionsFile = options.file as any;
    let ext = '';
    if (optionsFile && optionsFile.name) {
      let filename = optionsFile.name;
      ext = filename.substring(filename.lastIndexOf('.'));
    }
    let filename = `${props.filePath}/${uuid()}${ext}`;

    const fileData: qiniu.FileData = {
      type: 'file',
      filename: filename,
      data: options.file as any
    }
    let forceDirect = true;
    const newUploadTask = forceDirect
      ? qiniu.createDirectUploadTask(fileData, uploadConfig)
      : qiniu.createMultipartUploadV2Task(fileData, uploadConfig)

    newUploadTask.onProgress(progress => {
      //{size: 0, percent: 0.6666666666666666, details:{}
      console.log('progress', progress);
      options.onProgress && options.onProgress({ percent: progress.percent * 100 })
    })

    newUploadTask.onError(error => {
      console.log(error)
      options.onError && options.onError(error)
    })

    newUploadTask.onComplete(result => {
      //{"hash":"FhKOJmgsYAYDy7xG81nQuBHAdL40","key":"Square107x107Logo.png"}
      console.log('Complete', result);
      options.onSuccess && options.onSuccess(result)
    })
    newUploadTask.start()
  }, [props.filePath]);

  const onChange = ({ file, fileList: newFileList }) => {
    console.log(file, newFileList);
    setFileList(newFileList);
    setValues(newFileList.filter((item) => item.status === 'done').map((item) => {
      return item.response.key;
    }));
  };

  useEffect(() => {
    if (!props.values) return;
    //
    if (props.values == values) return;
    //
    if (props.values && props.values.length > 0) {
      qiniuGetUrl(props.values).then((urls) => {
        setValues(props.values);
        //获取文件
        setFileList(urls.map((item, index) => {
          return {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: item,
          }
        }));
      });
    }
  }, [props.values]);

  useEffect(() => {
    props.onChange && props.onChange(values);
  }, [props.onChange, values]);

  if (props.isPicture) {
    return (
      <ImgCrop rotationSlider>
        <Upload
          multiple={false}
          maxCount={props.max > 0 ? props.max : 1}
          listType={props.listType}
          accept={props.accept}
          fileList={fileList}
          customRequest={customRequest}
          onChange={onChange}
          onPreview={async (file: UploadFile) => {
            let src = file.url as string;
            if (!src) {
              src = await new Promise((resolve) => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj as FileType);
                reader.onload = () => resolve(reader.result as string);
              });
            }
            const image = new Image();
            image.src = src;
            const imgWindow = window.open(src);
            imgWindow?.document.write(image.outerHTML);
          }}
        >
          {fileList.length < (props.max > 0 ? props.max : 1) && (props.title ? props.title : '上传文件')}
        </Upload>
      </ImgCrop>
    );
  } else {
    return (
      <Upload
        multiple={false}
        maxCount={props.max > 0 ? props.max : 1}
        listType={props.listType}
        accept={props.accept}
        fileList={fileList}
        customRequest={customRequest}
        onChange={onChange}
      >
        <Button>{props.title ? props.title : '上传文件'}</Button>
      </Upload>
    );
  }
}




const Container = styled.div`
`;